import { defineStore } from 'pinia'
import { UserService } from '../services/users'

export const useUserStore = defineStore('user', {
  state: () => ({
    users: [],
    loading: false,
    error: null,
    selectedUser: null
  }),

  getters: {
    agents: (state) => state.users.filter(user => user.role === 'agent'),
    customers: (state) => state.users.filter(user => user.role === 'customer'),
    admins: (state) => state.users.filter(user => user.role === 'admin'),
    
    getUserById: (state) => (id) => {
      return state.users.find(user => user.id === id)
    },
    
    getUserTicketCount: (state) => (userId) => {
      // 这里需要从tickets store获取数据
      return 0 // 临时返回0，后续会从tickets store获取
    }
  },

  actions: {
    async fetchUsers(params = {}) {
      this.loading = true
      this.error = null
      try {
        console.log('📝 Store: 获取用户列表，参数:', params)
        const users = await UserService.listUsers(params)
        console.log('✅ Store: 获取用户列表成功，数量:', users?.length || 0)
        
        // 确保users始终是数组
        this.users = Array.isArray(users) ? users : []
        
        // 如果users为空数组，输出警告
        if (this.users.length === 0) {
          console.warn('⚠️ Store: 用户列表为空')
        }
      } catch (error) {
        console.error('❌ Store: 获取用户列表失败:', error)
        this.error = error.message || error.toString()
        // 发生错误时确保users仍是数组
        this.users = []
        // 不抛出错误，让界面能正常显示
      } finally {
        this.loading = false
      }
    },

    async createUser(userData) {
      this.loading = true
      this.error = null
      try {
        console.log('📝 Store: 创建用户，数据:', userData)
        const newUser = await UserService.createUser(userData)
        console.log('✅ Store: 用户创建成功，新用户:', newUser)
        
        // 确保users是数组
        if (!Array.isArray(this.users)) {
          this.users = []
        }
        
        // 将新用户添加到列表开头（如果新用户存在）
        if (newUser) {
          // 检查是否已存在（避免重复）
          const exists = this.users.some(u => u.id === newUser.id || u.username === newUser.username)
          if (!exists) {
            this.users.unshift(newUser)
            console.log('✅ Store: 新用户已添加到列表，当前用户数:', this.users.length)
          } else {
            console.log('ℹ️ Store: 用户已存在于列表中，跳过添加')
          }
        } else {
          console.warn('⚠️ Store: 创建成功但返回的用户数据为空')
        }
        
        // 返回新用户数据
        return newUser
      } catch (error) {
        console.error('❌ Store: 创建用户失败:', error)
        this.error = error.message || error.toString()
        // 抛出错误以便上层处理
        throw error
      } finally {
        this.loading = false
      }
    },

    async updateUser(userId, userData) {
      this.loading = true
      this.error = null
      try {
        const updatedUser = await UserService.updateUser(userId, userData)
        const index = this.users.findIndex(user => user.id === userId)
        if (index !== -1) {
          this.users[index] = updatedUser
        }
        return { success: true, data: updatedUser }
      } catch (error) {
        this.error = error.message
        return { success: false, message: error.message }
      } finally {
        this.loading = false
      }
    },

    async deleteUser(userId) {
      this.loading = true
      this.error = null
      try {
        await UserService.deleteUser(userId)
        this.users = this.users.filter(user => user.id !== userId)
        return { success: true }
      } catch (error) {
        this.error = error.message
        return { success: false, message: error.message }
      } finally {
        this.loading = false
      }
    },

    async updateUserPermissions(userId, permissions) {
      this.loading = true
      this.error = null
      try {
        const result = await UserService.updatePermissions(userId, permissions)
        const user = this.users.find(u => u.id === userId)
        if (user) {
          user.permissions = permissions
        }
        return { success: true, data: result }
      } catch (error) {
        this.error = error.message
        return { success: false, message: error.message }
      } finally {
        this.loading = false
      }
    },

    async batchUpdateRole(userIds, role) {
      this.loading = true
      this.error = null
      try {
        await UserService.batchUpdateRole(userIds, role)
        // 更新本地数据
        userIds.forEach(id => {
          const user = this.users.find(u => u.id === id)
          if (user) {
            user.role = role
          }
        })
        return { success: true }
      } catch (error) {
        this.error = error.message
        return { success: false, message: error.message }
      } finally {
        this.loading = false
      }
    },

    async batchUpdateStatus(userIds, status) {
      this.loading = true
      this.error = null
      try {
        await UserService.batchUpdateStatus(userIds, status)
        // 更新本地数据
        userIds.forEach(id => {
          const user = this.users.find(u => u.id === id)
          if (user) {
            user.active = status
          }
        })
        return { success: true }
      } catch (error) {
        this.error = error.message
        return { success: false, message: error.message }
      } finally {
        this.loading = false
      }
    },

    async batchDelete(userIds) {
      this.loading = true
      this.error = null
      try {
        await UserService.batchDelete(userIds)
        // 从本地列表中移除
        this.users = this.users.filter(u => !userIds.includes(u.id))
        return { success: true }
      } catch (error) {
        this.error = error.message
        return { success: false, message: error.message }
      } finally {
        this.loading = false
      }
    },

    setSelectedUser(user) {
      this.selectedUser = user
    },

    clearSelectedUser() {
      this.selectedUser = null
    }
  }
})